package sniff.diller;

import jpcap.packet.ARPPacket;
import jpcap.packet.Packet;
import sniff.pack.MyARPPacket;
import util.ByteUtil;
import util.InfoUtil;

public class ARPPacketDiller {

	public static MyARPPacket dill(Packet pack) {
		ARPPacket arpPack = (ARPPacket) pack;
		byte[] bs = arpPack.header;
		CommonHeadDiller hd = new CommonHeadDiller(bs);
		String destinationMAC = hd.getDestinationMAC();
		String sourceMAC = hd.getSourceMAC();
		String protocol = hd.getType();

		String htype = "";
		int hardtype = ByteUtil.unionByte(bs[14], bs[15]);
		switch (hardtype) {
		case ARPPacket.HARDTYPE_ETHER:
			htype = "Ethernet(以太网)";
			break;
		case ARPPacket.HARDTYPE_FRAMERELAY:
			htype = "帧中继";
			break;
		case ARPPacket.HARDTYPE_IEEE802:
			htype = "令牌环";
			break;
		default:
			htype = "unkown";
			break;
		}

		String protocolType = "unkown";
//		int prototype = ByteUtil.unionByte(bs[16], bs[17]);
		if (arpPack.prototype == ARPPacket.PROTOTYPE_IP) {
			protocolType = "IP";
		}

		int hlen = bs[18] & 0xff;
		int plen = bs[19] & 0xff;
		
		int opcode = ByteUtil.unionByte(bs[20], bs[21]);
		String operation = "unkown";

		String senderMac = "";
		int i = 22;
		for (int j=i+hlen; i < j; i++) {
			senderMac += ByteUtil.byteToHexString(bs[i]) + ":";
		}
		senderMac = senderMac.substring(0, senderMac.length() - 1);

		String senderIP = "";
		for (int j=i+plen; i < j; i++) {
			senderIP += ByteUtil.byteToInt(bs[i]) + ".";
		}
		senderIP = senderIP.substring(0, senderIP.length() - 1);

		String targetMac = "";
		for (int j=i+hlen; i < j; i++) {
			targetMac += ByteUtil.byteToHexString(bs[i]) + ":";
		}
		targetMac = targetMac.substring(0, targetMac.length() - 1);
		
		String targetIP = "";
		for (int j= i+plen; i < j; i++) {
			targetIP += ByteUtil.byteToInt(bs[i]) + ".";
		}
		targetIP = targetIP.substring(0, targetIP.length() - 1);

		String padding = "";
		for (; i < bs.length; i++) {
			padding += ByteUtil.byteToHexString(bs[i]) + " ";
		}
		if(padding.length()>0) {
			padding = padding.substring(0, padding.length() - 1);
		}
		
		int lenght = arpPack.len;
		
		switch (opcode) {
		case ARPPacket.ARP_REQUEST:
			operation = "request(1)";
			break;
		case ARPPacket.ARP_REPLY:
			operation = "reply(2)";
			break;
		default:
			break;
		}
		String info = "";
		MyARPPacket myArpPack = new MyARPPacket(destinationMAC, sourceMAC, protocol, htype, protocolType, hlen, plen,
				operation, senderMac, senderIP, targetMac, targetIP, padding, lenght, info, bs,arpPack.data);
		myArpPack.setInfo(InfoUtil.getARPInfo(myArpPack));
		return myArpPack;
	}

}
